'use strict';
const path = require('path');
const Controller = require('egg').Controller;
const sendToWormhole = require('stream-wormhole');
const md5 = require('md5')
class UntilController extends Controller {
    async sessionKeyget(){
        const {ctx,service,config} = this;
        const {code,userInfo,shoptoplvid} =ctx.request.body;
        let appinfo = await ctx.model.Other.findOne({shoptoplvid,name:'payinfo'});
        let {appid,appsecret} = appinfo.obj;
        let appId= appid;
        let appSecret = appsecret;
         // 示例：请求一个 npm 模块信息
        const result = await ctx.curl(`https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`,
         {dataType: 'json',timeout: 3000}
        );
        let info = result.data;
        let states = await service.user.getUserByid(info.openid);
        
        if(states.data==1){
            states.result.session_key = info.session_key;
            let updata =  await ctx.model.User.update({ openid: info.openid},{ $set: { nickName: userInfo.nickName, headimg: userInfo.headimg} });
            let userData = await service.user.getUserByid(info.openid);
            ctx.body = userData;
            return null;
        }else if(states.data==2){
            userInfo.openid = info.openid;
            if(userInfo.nickName.indexOf('rdgztest_')==0&&!userInfo.avatarUrl){
                ctx.body = userInfo;
                return null;
            }else{
                let resd = await service.normal.addinfo('User',userInfo); 
                if(resd.data==0){
                    ctx.body = resd;
                }else{
                    ctx.session.userId = info.openid;
                    ctx.session.isLogin = true;
                    resd.result = userInfo;
                    ctx.body = resd;
                }
                return null;
            }
        }else{
            ctx.body = states;
            return null;
        }
       
    }
    
    async wxcrypt(){
        const {ctx,service,config} = this;
        console.log(config.appId);
        const {sessionKey,iv,encryptedData}=ctx.request.body;
        let result = await service.user.wxcrypt(sessionKey,iv,encryptedData);
        ctx.body = {data:1,retult};
    }
    async upimg() {
        const {ctx,service} = this;
        let result = await service.normal.upfile('img','shopphoto');
        ctx.body = {data:1,url:result.url};
    }
    async getother(){
        const {ctx,service} = this;
        const json = ctx.request.query;
        let result = await ctx.model.Other.findOne(json).exec();
        await service.normal.isresult(result);
        ctx.body = {data:1,result};
    }
    async getothers(){
        const {ctx,service} = this;
        const json = ctx.request.query;
        let result = await ctx.model.Other.find(json).exec();
        await service.normal.isresult(result);
        ctx.body = {data:1,result};
    }
}

module.exports = UntilController;